import { login, logout, getInfo } from '@/api/acl/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,allAsyncRoutes,constantRoutes,anyRoute } from '@/router'
import router from '@/router'

// const getDefaultState = () => {
//   return {
//     token: getToken(),
//     name: '',
//     avatar: ''
//   }
// }

// const state = getDefaultState()
// 根据返回的路由名称数组过滤真正的异步数组
function filterUserAsyncRoutes(allAsyncRoutes,routeNames){
  const result = allAsyncRoutes.filter(item => {
    if(routeNames.indexOf(item.name) !== -1){
      if(item.children && item.children.length > 0){
        item.children = filterUserAsyncRoutes(item.children,routeNames)
      }
      return true
    }
  })
  return result
}

const state ={
  token:getToken(),
  name:'',
  avatar:'',
  buttons:[],
  roles:[],
  asyncRoutes:[], // 准备放用户返回的字符串信息对应的真正的异步路由数组
  routes:[]  // 代表这个用户对应的所有的路由数组,用于后期动态生成菜单
}

const mutations = {
  RESET_STATE: (state) => {
    // Object.assign(state, getDefaultState())
    state.name = '',
    state.avatar = '',
    state.token = getToken()
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // SET_NAME: (state, name) => {
  //   state.name = name
  // },
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // }

  SET_USERINFO(state,userInfo){
    state.name = userInfo.name,
    state.avatar = userInfo.avatar,
    state.buttons = userInfo.buttons,
    state.roles = userInfo.roles
  },

  SET_ROUTES(state,asyncRoutes){
    state.asyncRoutes = asyncRoutes
    state.routes = constantRoutes.concat(asyncRoutes,anyRoute)
    // 动态路由注册
    // router.addRoutes([...asyncRoutes,anyRoute])
    router.addRoutes([...asyncRoutes,anyRoute])
  }
}
 
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        // const { name, avatar } = data

        // commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)

        commit('SET_USERINFO',data)
        commit('SET_ROUTES',filterUserAsyncRoutes(allAsyncRoutes,data.routes))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true, //开启命名空间,开启后,对应的actions,mutations,getters 可以重名
  state,
  mutations,
  actions
}

